import React, { useEffect, useRef, useState } from 'react'
import { Button, Switch, Table, Space, Modal, message } from 'antd'
import { PlusOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { addUser, delUser, editUser, getRegions, getUserList, setSwitch } from '@/api/user'
import { DeleteOutlined } from '@ant-design/icons'
import { getPermission } from '@/api/permission'
import OpenForm from './modules/OpenForm'
// 菜单功能限制
import { filterRoles, filterRegions } from '@/utils/jurisdiction'
export default function User() {
    const [userList, setUserList] = useState([])
    const [open, setopen] = useState(false) // dialog
    const [regions, setRegions] = useState([]) // 区域数据
    const [rolesList, setRolesList] = useState([]) // 角色数据
    const [isRegionDisabled, setIsRegionDisabled] = useState(false) // // 子组件表单是否禁用
    const [isEdit, setIsEdit] = useState(false) // 是否是修改状态
    const openFormRef = useRef(null)
    const editId = useRef(null)
    useEffect(() => {
        loadUserList()
        openRegions()
    }, [])
    // 获取用户列表
    const loadUserList = async () => {
        const { data } = await getUserList()
        setUserList(data)
    }
    // dialog打开
    const openHandel = async (item) => {
        console.log(item)
        if (item) {
            setopen(true)
            setIsEdit(true) // 切换为编辑状态
            // 会出现From还未创建,需要进入异步队列
            setTimeout(() => {
                openFormRef.current.setFieldsValue(item)
            }, 0)
            editId.current = item.id
            if (item.roleId === 1) {
                setIsRegionDisabled(true)
            } else {
                setIsRegionDisabled(false)
            }
        } else {
            setopen(true)
            setIsEdit(false) // 切换为添加状态
        }
        if (rolesList.length === 0) {
            openRolesList()
        }
    }
    // 获取区域数据
    const openRegions = async () => {
        const { data } = await getRegions()
        console.log(data, '区域')
        setRegions(filterRegions(data))
    }
    // 获取角色
    const openRolesList = async () => {
        const { data } = await getPermission()
        console.log(data)
        setRolesList(filterRoles(data))
    }
    // 
    // 弹框
    const confirmHandel = (item) => {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '此操作将删除该用户, 是否继续？',
            okText: '确认',
            onOk: () => { delHandel(item) },
            cancelText: '取消',
            onCancel: () => {
            }
        })
    }
    // 删除函数
    const delHandel = async (item) => {
        await delUser({ id: item.id })
        message.open({
            type: 'success',
            content: '删除成功',
        })

        loadUserList()
    }
    // 添加保存
    const onOkHandel = () => {
        // 兜底验证
        openFormRef.current.validateFields()
            .then(async (value) => {
                isEdit ? await edit(value) : await add(value)
                message.open({
                    type: 'success',
                    content: '添加成功',
                })
                openFormRef.current.resetFields()
                setopen(false)
                loadUserList()
            })
            .catch()
        // console.log(openFormRef.current)
    }
    // 添加
    const add = async (value) => {
        await addUser({
            ...value,
            roleState: true, // 开关默认开
            default: false, // 默认不禁用
        })
    }
    // 修改
    const edit = async (value) => {
        await editUser({
            ...value,
            id: editId.current,
            roleState: true, // 开关默认开
            default: false, // 默认不禁用
        })
    }
    // 开关改变
    const switchChangeHandel = async (item) => {
        await setSwitch({
            id: item.id,
            roleState: !item.roleState
        })
        message.open({
            type: 'success',
            content: '操作成功',
        })
        loadUserList()
    }
    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            render: (region) => {
                return <div>{region === '' ? '全球' : region}</div>
            },
            filters: [
                ...regions.map(item => {
                    return {
                        text: item.title,
                        value: item.value
                    }
                }),
                {
                    text: '全球',
                    value: ''
                }
            ],
            onFilter: (value, record) => value === record.region
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render: (role) => {
                return role.roleName
            },
        },
        {
            title: '用户名',
            dataIndex: 'username',
        },
        {
            title: '用户状态',
            render: (roleState, item) => {
                return (
                    <Switch
                        disabled={item.default}
                        defaultChecked={item.roleState}
                        onClick={() => switchChangeHandel(item)}
                    />
                )
            }
        },
        {
            title: '操作',
            render: (item) => {
                return (
                    <Space>
                        <Button type="primary" shape="circle"
                            disabled={item.default}
                            icon={<EditOutlined />}
                            onClick={() => openHandel(item)}
                        />
                        <Button danger shape="circle"
                            disabled={item.default}
                            icon={<DeleteOutlined />}
                            onClick={() => {
                                confirmHandel(item)
                            }}
                        />
                    </Space>
                )
            }
        },
    ]
    return (
        <>
            <Button icon={<PlusOutlined />} type="primary"
                onClick={() => openHandel()}
            >
                添加用户
            </Button>
            <Table
                columns={columns}
                dataSource={userList}
                rowKey={(item) => item.id}
                pagination={
                    {
                        pageSize: 5
                    }
                }
            />
            <Modal
                destroyOnClose // Modal在关闭时将会销毁
                open={open}
                title={(isEdit ? '修改' : '添加') + '用户信息'}
                cancelText="取消"
                onCancel={() => {
                    setopen(false)
                    openFormRef.current.resetFields()
                }}
                okText="确定"
                onOk={() => onOkHandel()}
            >
                <OpenForm
                    ref={openFormRef}
                    regions={regions}
                    rolesList={rolesList}
                    isRegionDisabled={isRegionDisabled}
                    setIsRegionDisabled={(bln) => setIsRegionDisabled(bln)}
                />
            </Modal>
        </>
    )
}
